<?php

namespace App\Api\Middleware;

use App\Api\Services\JsonService;
use App\Api\Services\Token;
use Closure;
use Illuminate\Http\Request;

class AppVerification
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {

        $token = $request->bearerToken();
        if (!isset($token) || empty($token)){
            return response()->json(array('code' => 1001, 'msg' =>'接口鉴权失败','data'=>'' ));
        }
        $memberId = $request->query('member_id') ?? '';
        if ( !isset($memberId) || empty($memberId) ){
            return response()->json(array('code' => 1001, 'msg' =>'接口鉴权失败,缺少用户唯一标识','data'=>'' ));
        }
        $data = Token::ParseToken($token);
        if (!$data || $data['code'] !=200){
            return response()->json(array('code' => 1001, 'msg' =>$data['msg'],'data'=>'' ));
        }

        if($memberId  != $data['data']->member_id){
            return response()->json(array('code' => 1001, 'msg' =>'验证失败 用户权限不足','data'=>'' ));
        }

        return $next($request);
    }
}
